import { Component } from '@angular/core';

import { AlertController, App, ModalController, NavController, NavParams } from 'ionic-angular';

import { InfoListService } from './list.service';

import { Config } from '../../../providers/config';

import { InfoDetailPage } from '../detail/detail.component';

import _ from 'lodash';

@Component({
  selector: 'page-info-list',
  templateUrl: './list.html',
  providers: [InfoListService]
})
export class InfoListPage {
	moa_page_name: any = "page-info-list";
  moa_page_explain: any = "";

  // 列表数据
  listData: any = [];
  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  type = "";

  title = "";

  _ = _;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public listService: InfoListService,
    public config: Config,
    public navParams: NavParams
  ) {
    this.type = this.navParams.get('type');
    if (this.type == 'tips') {
      this.title = '温馨提示';
    }
    if (this.type == 'notic') {
      this.title = '通知公告';
    }
    if (this.type == 'dispatch') {
      this.title = '正式发文';
    }

    this.moa_page_explain = this.title;

    // 初始化数据
    this.loadListData(this.pageIndex, null, null);
  }
  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(page, infiniteScroll, refresher) {
    this.listService.getListData(page, this.type).subscribe(data => {
      if (data) {
        console.info(data);
        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData = _.concat(this.listData, data);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;
        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  }
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    console.info(item);
    item.oaType = this.type;
    this.navCtrl.push(InfoDetailPage, item);
  }

  ionViewDidLoad() {

  }
  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.isLoadMore) {
      this.loadListData(this.pageIndex, infiniteScroll, null);
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    this.loadListData(this.pageIndex, null, refresher);
  }

}
